<template>
  <div>
    <el-row>
      <el-col :span="6" :push="15">
        <es-login-form @login="login" ref="form" disable-register/>
      </el-col>
    </el-row>
  </div>
</template>

<script>
import EsLoginForm from "@/components/EsLoginForm";
import axios from "axios";
import md5 from "md5";
import Cookies from "js-cookie";

export default {
  name: "ManagerLoginView",
  components: {
    EsLoginForm
  },
  methods: {
    login(form) {
      let loading = this.$loading({
        fullscreen: true,
        lock: true
      })
      let username = form.username;
      let password = form.password;
      axios.post('/api/account/login', {username, password: md5(password), permission: 1})  // 特权级1, 特权用户
          .then(res => {
            Cookies.set("sessionID", res.data)
            this.$store.commit("setUsername", username)
            this.$store.commit("setIsAdmin", true)
            loading.close()
            this.$router.replace("/manager")  // back to home
          })
          .catch(e => {
            if (e.response) {
              if (e.response.status === 403) {
                this.$alert("用户名或密码错误", {
                  type: "error"
                })
                    .then(() => {
                      loading.close()
                    })
              } else {
                this.$message({
                  message:  `未知的服务器错误, 代码 ${e.response.status}`,
                  type: "error"
                })
                loading.close()
              }
            }
            else {
              this.$message({
                message: "未知的错误",
                type: "error"
              })
              loading.close()
            }
          })
    },
  }
}
</script>

<style scoped>

</style>